import { ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

export default function useMap() {
  // 城市定位
  const city = ref('')
  const adcode = ref('')
  const poisList = ref([] as any[])
  const defaultCheck = ref('')
  const handleCitySearch = () => {
    // 创建城市查询实例
    const citysearch = new (AMap as any).CitySearch()
    // 自动获取用户IP，返回当前城市
    citysearch.getLocalCity(function (status: string, result: any) {
      if (status === 'complete' && result.info === 'OK') {
        if (result && result.city && result.bounds) {
          console.log(result);
          city.value = result.addressComponent.citycode
          console.log(result)
          console.log(city.value)
        }
      }
    })
  }
  // 用户web端定位
  const handleGeoLocation = () => {
    const geolocation = new (AMap as any).Geolocation({
      enableHighAccuracy: true, // 是否使用高精度定位，默认：false
      timeout: 10000, // 设置定位超时时间，默认：无穷大
      offset: [10, 20], // 定位按钮的停靠位置的偏移量
      panToLocation: true,
      zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      position: 'RB', //  定位按钮的排放位置,  RB表示右下
      needAddress: true, // 将定位结果进行逆地理编码操作
      extensions: 'all', // 需要详细的逆地理编码信息
    })

    geolocation.getCurrentPosition(function (status: string, result: any) {
      if (status == 'complete') {
        console.log(result)
        city.value = result.addressComponent.city
        adcode.value = result.addressComponent.citycode
        poisList.value = result.pois
        defaultCheck.value = poisList.value[0].id
      } else {
        console.log(result)
      }
    })
  }
  // 逆地址解析
  const handleAddress = (lat: number, lng: number): Promise<any> => {
    return new Promise((resolve, reject) => {
      const geocoder = new (AMap as any).Geocoder({ city: city });
      const lnglat = [lng, lat];
      geocoder.getAddress(lnglat, function (status: string, result: any) {
        if (status === 'complete' && result.info === 'OK') {
          resolve(result);
          console.log(result);
        } else {
          reject(new Error('地址解析失败'));
        }
      });
    });
  };
  // const handleAddress = (lat: number, lng: number) => {
  //   const geocoder = new (AMap as any).Geocoder({
  //     city: city, // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
  //   })
  //   const lnglat = [lng, lat]
  //   // var lnglat = [116.396574, 39.992706];
  //   geocoder.getAddress(lnglat, function (status: string, result: any) {
  //     if (status === 'complete' && result.info === 'OK') {
  //       // result为对应的地理位置详细信息
  //       console.log(result)
  //       city.value = result.regeocode.addressComponent.city
  //       localStorage.setItem(
  //         'geolocation',
  //         JSON.stringify({ city: result.regeocode.addressComponent.city, lng: lng, lat: lat }),
  //       )
  //       return result
  //     } else {
  //       console.log('地址解析失败')
  //     }
  //   })
  // }

  // 加载高德地图
  const loadMap = () => {
    return new Promise<void>((resolve, reject) => {
      window._AMapSecurityConfig = {
        securityJsCode: 'ee05fab28178bddab609e5fc3227b733',
      }
      AMapLoader.load({
        key: 'cee8ccb46c652903c16c0630171e08cf',
        version: '2.0',
        plugins: [
          'AMap.Geocoder',
          'AMap.Geolocation',
          'Amap.CitySearch',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.Geocoder',
        ],
      })
        .then(() => {
          resolve()
        })
        .catch((e) => {
          if (e instanceof Error) {
            if (e.message.includes('Invalid API key')) {
              console.error('高德地图API密钥无效，请检查您的API密钥是否正确')
            } else if (e.message.includes('Network error')) {
              console.error('网络错误，请检查您的网络连接是否正常')
            } else {
              console.error('加载高德地图API时出现其他错误：', e)
            }
          } else {
            console.error('加载高德地图API时出现未知错误：', e)
          }
          reject(e)
        })
    })
  }
  return {
    adcode,
    defaultCheck,
    poisList,
    city,
    loadMap,
    handleAddress,
    handleCitySearch,
    handleGeoLocation,
  }
}
